import { getInfo } from '@/api/user'
import { login, logout } from '@/api/login'
import { getPermission } from '@/api/menu'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  role: '',
  name: '',
  mobile: '',
  avatar: '',
  token: '',
  menus: ''
}

const mutations = {
  SET_ROLE: (state, role) => {
    state.role = role
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_MOBILE: (state, mobile) => {
    state.mobile = mobile
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  }
}

const actions = {
  // get permission menu
  getPermission({ commit, state }, data) {

    return new Promise((resolve, reject) => {
      getPermission(data).then(response => {
        const { data } = response

        if (!data) {
          reject('获取菜单失败，认证失败，请重新登录')
        }

        // const { roles, name, avatar, introduction } = data

        // roles must be a non-empty array
        /*if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }*/

        /*commit('SET_ROLES', roles)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_INTRODUCTION', introduction)*/
        /*const menus =
          [
            {
              path: '/from',
              component: 'Layout',
              children: [{
                path: 'form',
                name: 'AddressBook',
                component: '/example/list',
                meta: { title: '通讯录', icon: 'user' }
              }]
            },
            {
              path: '/permission',
              component: 'Layout',
              redirect: '/permission/page',
              name: 'Permission',
              meta: { title: '权限页面', icon: 'lock' },
              children: [
                {
                  path: 'page',
                  name: '角色权限',
                  redirect: '',
                  component: '/permission/page',
                  meta: { title: '角色权限', icon: '' },
                  children: []
                },
                {
                  path: 'directive',
                  name: '指令权限',
                  redirect: '',
                  component: '/permission/directive',
                  meta: { title: '指令权限', icon: '' },
                  children: []
                }
              ]
            }
          ]*/

        /*
        *  程宇 2021-11-11
        *  给菜单加上新增的流动红旗页面路由
        */
        // data.forEach(it => {
        //   if (it.path === '/flow') {
        //     it.children.push({
        //       children: [],
        //       path: '/flow/demo',
        //       component: '/flow/Demo',
        //       meta: { icon: '', title: '流动红旗扣分规则' },
        //       name: 'flowdemo'
        //     })
        //   }
        // })
        const menus = data
        commit('SET_MENUS', menus)
        window.sessionStorage.setItem('menus', JSON.stringify(menus))
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    commit('SET_MENUS', '')
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
